import {RouteLocationNormalized, NavigationGuardNext} from "vue-router"
import appPinia from "@/pinia/app"
import {userInfo} from "@/api/login"
import {RouterComponent} from "src/type"
import router from "@/router/index"
import isArray from "lodash/isArray.js"
import {reBuildIcon} from "@/utils/utils"

const namespace = "main"
//框架页面组件
const views: Record<string, RouterComponent> = import.meta.glob("@/view/**/*.vue", {eager: true})

function findComponent(filePath: string) {
    const key = Object.keys(views).find((path) => {
        return path.toLowerCase().indexOf(filePath.toLowerCase()) > -1
    })

    if (key != undefined) {
        return filePath && views[key] && views[key].default
    } else {
        return null
    }
}


function addRouter(item: any) {
    if (item.component) {
        const component = findComponent(item.component+".vue")
        if (component) {
            router.addRoute(item.namespace ? item.namespace : namespace, {
                path: item.router, name: item.title, component: component, meta: item
            })
        }
    }
}

/**
 * 创建路由组件
 * @param allMenus
 */
function createRouterComponent(allMenus: any) {
    allMenus.forEach((item: any) => {
        addRouter(item)
        if (isArray(item.children)) {
            createRouterComponent(item.children)
        }
    })
}

/**
 * 校验路由是否在白名单中
 * @param path
 */
function hasWhiteRouter(path: string) {
    const appStore = appPinia()
    return appStore.configOptions.whiteList.some((e: string) => path.indexOf(e) === 0)
}

/**
 * 是否登录
 */
function hasUserInfo() {
    const appStore = appPinia()
    return Object.keys(appStore.userInfo).length !== 0
}

/**
 * 获取并更新用户信息
 * @param to
 * @param from
 * @param next
 */
function getUserInfo(to: RouteLocationNormalized, from: RouteLocationNormalized, next: NavigationGuardNext) {
    const appStore = appPinia()
    userInfo().then((res) => {
        appStore.userInfo = res.data
        appStore.treeMenus = res.data.menu
        updateRouterAll(to, from, next)
    }).catch(() => {
        next(appStore.configOptions.resetPath)
    })
}


/**
 * 获取后端接口菜单数据
 * @param to
 * @param from
 * @param next
 */
function updateRouterAll(to: RouteLocationNormalized, from: RouteLocationNormalized, next: NavigationGuardNext) {
    const appStore = appPinia()
    if (appStore.hasRoles) {
        next()
    } else {
        const appStore = appPinia()
        appStore.treeMenus = reBuildIcon(appStore.treeMenus)
        createRouterComponent(appStore.treeMenus)
        next(to.fullPath)
        appStore.hasRoles = true
    }
}

const beforeEach = (to: RouteLocationNormalized, from: RouteLocationNormalized, next: NavigationGuardNext) => {
    if (hasWhiteRouter(to.path)) {
        return next()
    }
    if (hasUserInfo()) {
        updateRouterAll(to, from, next)
    } else {
        getUserInfo(to, from, next)
    }
}

export default beforeEach
